﻿using log4net.Core;
using MongoDB.Bson;

namespace log4net.extension.mongo
{
    /// <summary>
    /// 默认格式 MongoLogEntity
    /// </summary>
    public class DefaultMongoAppender : MongoAppenderBase
    {
        protected override BsonDocument Convert(LoggingEvent loggingEvent)
        {
            var entity = BuildLogEntity(loggingEvent);
            return entity.ToBsonDocument();
        }

        private MongoLogEntity BuildLogEntity(LoggingEvent loggingEvent)
        {
            string message = string.Empty;
            string exceptionStr = loggingEvent.GetExceptionString();
            if (exceptionStr != null && exceptionStr.Length > 0)
                message = string.Format("{0}\r\n{1}", loggingEvent.RenderedMessage, exceptionStr);
            else
                message = loggingEvent.RenderedMessage;

            return new MongoLogEntity
            {
                LogTime = loggingEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss"),
                Level = loggingEvent.Level.DisplayName,
                Domain = loggingEvent.Domain,
                ServerIp = m_localIp,
                Message = message
            };
        }
    }
}
